// components/auth/index.js
import wxRequest from '../../utils/wxRequest.js'
const app = getApp();
Component({
  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    bindGetUserInfo(res) {
      console.log(res);
      let data = res.detail;
      if (data.errMsg == 'getUserInfo:ok') {
        let userInfo = res.detail.userInfo;
        let iv = res.detail.iv;
        let encryptedData = res.detail.encryptedData;
        this.login(userInfo, iv, encryptedData);
      }
    },
    login(userInfo, iv, encryptedData) {
      wx.login({
        success: data => {
          let code = data.code
          wxRequest.getRequest('/m/api/wx_login', {
            userinfo: JSON.stringify(userInfo),
            iv,
            encryptedData,
            code: code,
          }).then(res => {
            console.log('success', res)
            let token = res.data.token;
            let userInfo = res.data.userinfo
            wx.setStorageSync('t', token)
            wx.setStorageSync('userInfo', userInfo)
            app.globalData.userInfo = userInfo;
            app.userInfoReadyCallback({
              userInfo : userInfo
            })
          }).catch(error => {
            if (error.code) {
              wx.showToast({
                title: error.message,
                icon: 'none'
              })
              
            }else{
              wx.showToast({
                title:'授权失败',
                icon: 'none'
              })
            }
            console.log('error', error)
          })
        }
      })
    },
  }
})